package pers.qianyu.month_202011.date_20201116;

import pers.qianyu.util.*;

/**
 * 567. 字符串的排列
 * https://leetcode-cn.com/problems/permutation-in-string/
 *
 * @author mizzle rain
 * @date 2020年11月16日13:21:44
 */
public class CheckInclusion4 {
    /**
     * 再次优化哈希表
     */
    public boolean checkInclusion(String s1, String s2) {
        int left = 0, right = s1.length() - 1;
        int[] need = new int[26];
        int[] window = new int[26];
        for (int i = 0; i < s1.length(); i++) {
            need[s1.charAt(i) - 'a']++;
            if (i < s2.length()) {
                window[s2.charAt(i) - 'a']++;
            }
        }
        while (right < s2.length() - 1) {
            if (isValid(need, window)) {
                return true;
            }
            window[s2.charAt(left++) - 'a']--;
            window[s2.charAt(++right) - 'a']++;
        }
        return isValid(need, window);
    }

    private boolean isValid(int[] need, int[] window) {
        for (int i = 0; i < 26; i++) {
            if (need[i] != window[i]) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String s1 = "abcdxabcde";
        String s2 = "abcdeabcdx";
        ArrayUtil.printIndex(s2.length());
        CheckInclusion4 c = new CheckInclusion4();
        boolean result = c.checkInclusion(s1, s2);
        System.out.println("result = " + result);
    }
}
